﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using BusinessFacade;
using EntityManage;
using System.Text;

public partial class Modules_Personal_FirstAssignOrg : System.Web.UI.Page
{
    IPerf_Personal_TargetOwnerHandler toHandler = new Perf_Personal_TargetOwnerManage();
    ISys_UserHandler userHandler = new Sys_UserManage();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();
    ISys_OrganizationHandlerExt orgExtHandler = new Sys_OrganizationManageExt();
    ISys_PostHandler postHandler = new Sys_PostManage();
    IPerf_Personal_FirstAssignHandler firstAssignHandler = new Perf_Personal_FirstAssignManage();
    IPerf_Flow_TraceHandler flowTraceHandler = new Perf_Flow_TraceManage();
    IPerf_Personal_ModTargetHandler modTargetHandler = new Perf_Personal_ModTargetManage();
    IPerf_Personal_FinalAssignHandler finalHandler = new Perf_Personal_FinalAssignManage();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "ID";
            ViewState["Accending"] = "desc";

            SqlParameter[] parms = null;
            string sql = " 1=1 ";
            ProcessParms(ref sql, ref parms);
            dataBind(sql, parms);
          
        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("302020"))
            {
            }
            else
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    #region DataBind
    
    /// <summary>
    /// 初始化岗位信息表
    /// </summary>
    private void dataBind(string whereClause, SqlParameter[] parms)
    {
        try
        {
            FillSearchDDL();

            SqlParameter[] parms2 = null;
            int counter = 0;
            DataTable dt = new DataTable();
            int searchPostId = 0;

            if (ViewState["SearchPostID"] != null)
            {
                searchPostId = int.Parse(ViewState["SearchPostID"].ToString());
            }

            // 读取本单位
            int userId = int.Parse(Session["CurrentUserID"].ToString());
            Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(userId);
            string orgIds = orgExtHandler.GetAllChildIdsByParentID(userQuery.Org_ID);
            orgIds = (orgIds.Length > 0 ? orgIds + "," + userQuery.Org_ID.ToString() : userQuery.Org_ID.ToString());
            Sys_UserQuery[] userList = userHandler.GetSys_UserQueryList(" (Org_ID in (" + orgIds + ") or Org_ID2 in (" + orgIds + ")) and Status = @Status"
                , new SqlParameter[] { new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid)});
            List<string> orgIdList = new List<string>();
            orgIdList.AddRange(orgIds.Split(','));
            StringBuilder assignIds = new StringBuilder();
            if (userList != null && userList.Length > 0)
            {
                foreach (Sys_UserQuery user in userList)
                {
                    int userOrgId = (user.Org_ID2 != 0 ? user.Org_ID2 : user.Org_ID);
                    int userPostId = (user.Post_ID2 != 0 ? user.Post_ID2 : user.Post_ID);

                    if (orgIdList.Contains(userOrgId.ToString()) && user.Assign_ID != 0 && (searchPostId == 0 || userPostId == searchPostId))
                    {
                        assignIds.Append(user.Assign_ID);
                        assignIds.Append(",");
                    }
                }
                assignIds = assignIds.Length > 0 ? assignIds.Remove(assignIds.Length - 1, 1) : assignIds;
            }

            whereClause += " and ID in(" + assignIds.ToString() + ")";

            dt = finalHandler.GetPerf_Personal_FinalAssignByPageList(whereClause, parms, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
            //whereClause = "1=1";
            //ProcessParms(ref whereClause, ref parms2);
            counter = finalHandler.GetCounter(whereClause, parms);

            this.AspNetPager.RecordCount = counter;
            gvFinalAssignList.DataSource = dt;
            gvFinalAssignList.DataBind();
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();

        parms = lstParm.ToArray();
    }

    private void FillSearchDDL()
    {
        FillSearchPost();
    }

    private void FillSearchPost()
    {
        DataTable dt = postHandler.GetSys_PostList(" Status = @Status", new SqlParameter[]{ new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid)}, " Name asc");
        ddlSearchPost.DataTextField = "Name";
        ddlSearchPost.DataValueField = "ID";
        ddlSearchPost.DataSource = dt;
        ddlSearchPost.DataBind();
        ddlSearchPost.Items.Insert(0, new ListItem("全部....","0"));
    }

    #endregion

    #region gvFinalAssignList

    protected void gvFinalAssignList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //
    }

    protected void gvFinalAssignList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex > -1)
            {
                string org = "";
                string org2 = "";
                string post = "";
                string post2 = "";

                Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(int.Parse(e.Row.Cells[1].Text));
                if (userQuery != null)
                {
                    e.Row.Cells[1].Text = userQuery.Name;

                    Sys_OrganizationQuery orgQuery = orgHandler.GetSys_OrganizationQuery(userQuery.Org_ID);
                    org = orgQuery != null ? orgQuery.Name : org;

                    if (userQuery.Org_ID2 != 0)
                    {
                        orgQuery = orgHandler.GetSys_OrganizationQuery(userQuery.Org_ID2);
                        org2 = orgQuery != null ? orgQuery.Name : org2;
                    }

                    Sys_PostQuery postQuery = postHandler.GetSys_PostQuery(userQuery.Post_ID);
                    post = postQuery != null ? postQuery.Name : post;

                    if (userQuery.Post_ID2 != 0)
                    {
                        postQuery = postHandler.GetSys_PostQuery(userQuery.Post_ID2);
                        post2 = postQuery != null ? postQuery.Name : post2;
                    }
                }
                e.Row.Cells[2].Text = org;
                e.Row.Cells[3].Text = post;
                e.Row.Cells[4].Text = org2;
                e.Row.Cells[5].Text = post2;

                // 指标套
                Perf_Personal_TargetOwnerQuery toQuery = toHandler.GetPerf_Personal_TargetOwnerQuery(int.Parse(e.Row.Cells[6].Text));
                if (toQuery != null)
                    e.Row.Cells[6].Text = toQuery.Name;

            }
        }
    }

    protected void gvFinalAssignList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        RefreshDataGridView();
    }

    #endregion

    #region Button
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (!ddlSearchPost.SelectedValue.Equals("0"))
            ViewState["SearchPostID"] = ddlSearchPost.SelectedValue;
        else
            ViewState["SearchPostID"] = null;

        RefreshDataGridView();
    }

    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {
        RefreshDataGridView();
    }

    #endregion

    private void RefreshDataGridView()
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }
}
